% 读取图像并灰度化
image = imread('pic_measure.png');
gray_image = rgb2gray(image);

% 对比度增强
enhanced_image = histeq(gray_image);

% 显示增强效果
imwrite(enhanced_image, 'contrast_enhanced.png');

imhist(enhanced_image);

% 转换为二值图像
bw = imbinarize(enhanced_image);

imshow(bw);

% 距离变换
dist_trans = -bwdist(~bw);
% disp(dist_trans);

% 对距离变换应用分水岭
L = watershed(dist_trans);
% disp(L);
bw(L == 0) = 0; % 将分割线设置为背景

% 显示分水岭结果
imwrite(bw, 'watershed_result.png');

% 检测边缘
edges = edge(enhanced_image, 'Canny', [0.1, 0.3]);

% 霍夫变换检测直线
[H, T, R] = hough(edges);
P = houghpeaks(H, 5); % 提取前5条显著直线
lines = houghlines(edges, T, R, P, 'FillGap', 10, 'MinLength', 30);

% 显示检测结果
figure;
imshow(edges);
hold on;

for k = 1:length(lines)
    xy = [lines(k).point1; lines(k).point2];
    plot(xy(:,1), xy(:,2), 'LineWidth', 2, 'Color', 'green');
end

hold off;

% 提取边缘坐标
[y_coords, x_coords] = find(edges);

% 使用多项式拟合连接边缘
p = polyfit(x_coords, y_coords, 2); % 二次拟合
x_fit = linspace(min(x_coords), max(x_coords), 100);
y_fit = polyval(p, x_fit);

% 显示拟合结果
figure;
imshow(edges);
hold on;
plot(x_fit, y_fit, 'r-', 'LineWidth', 2);
hold off;

% 保存拟合结果
imwrite(edges, 'edge_fit_result.png');
